import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'address_model.dart';
import 'logic.dart';
import 'state.dart';

typedef _onEventAddressSelectorCallBack = void Function(String name, List<String> areaIds);

class AddressSelectorPage extends StatefulWidget {
  // 这个是我们网络拉取的数据，根据实际你所需要的去变。应该是个树形结构的model
  AddressInfoModel spaceData;
  // List spaceData;

  AddressSelectorPage({this.spaceData, this.eventAreaDialogCallBack});

  // 选中后的callback
  _onEventAddressSelectorCallBack eventAreaDialogCallBack;

  @override
  _AddressSelectorPageState createState() => _AddressSelectorPageState();
}

class _AddressSelectorPageState extends State<AddressSelectorPage> with TickerProviderStateMixin {
  final AddressSelectorLogic logic = Get.put(AddressSelectorLogic());
  final AddressSelectorState state = Get.find<AddressSelectorLogic>().state;

  @override
  void initState() {
    super.initState();

    state.tabController = TabController(initialIndex: 0, length: 4, vsync: this);
    state.tabController.addListener(() {
      // 点击tab时或滑动tab回调一次
      if (state.tabController.index == state.tabController.animation.value) {
        // logic.changeTab(state.tabController.index);
      }
    });
  }

  @override
  void dispose() {
    super.dispose();
    state.tabController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: AnimatedPadding(
        padding: MediaQuery.of(context).viewInsets, //边距（必要）
        duration: const Duration(milliseconds: 100), //时常 （必要）
        child: Container(
          decoration: BoxDecoration(
            borderRadius: BorderRadius.only(
              topLeft: Radius.circular(20),
              topRight: Radius.circular(20),
            ),
            color: Colors.white,
          ),
          height: 350,
          child: Flex(
            direction: Axis.vertical,
            children: <Widget>[
              Container(
                padding: new EdgeInsets.only(left: 10, right: 10),
                height: 40,
                child: Scaffold(
                  backgroundColor: Colors.transparent,
                  appBar: TabBar(
                    controller: state.tabController,
                    unselectedLabelColor: Colors.red,
                    labelColor: Colors.red,
                    indicatorColor: Colors.red,
                    labelStyle: TextStyle(fontSize: 16),
                    isScrollable: true,
                    indicatorWeight: 3,
                    indicatorSize: TabBarIndicatorSize.label,
                    indicatorPadding: new EdgeInsets.fromLTRB(8, 0, 8, 0),
                    onTap: (index) {
                      if (!mounted) {
                        return;
                      }
                      setState(() {
                        //获取当前tab有多少
                        int size = state.tabs.length;
                        //记录当前位置
                        state.currentTabPos = index;
                        //循环处理，将当前位置之后的数据去除
                        for (int i = size; i > state.currentTabPos + 1; i--) {
                          state.tabs.removeAt(i - 1);
                          state.selectDatas.remove(i - 1);
                          state.selectNameDatas.remove(i - 1);
                        }

                        //将当前tab移动到选中的位置上
                        state.tabController.animateTo(state.currentTabPos);
                      });
                    },
                    tabs: state.tabs.map((e) => Tab(text: e)).toList(),
                  ),
                ),
              ),
              Expanded(
                  flex: 1,
                  child: TabBarView(
                    children: _buildPages(),
                    controller: state.tabController,
                    physics: NeverScrollableScrollPhysics(),
                  )),
            ],
          ),
        ),
      ),
    );
  }

  /**
   *创建tab界面
   */
  List<Widget> _buildPages() {
    List<Widget> pages = List();
    for (int i = 0; i < state.tabs.length; i++) {
      Widget page = new ListView.builder(
        padding: EdgeInsets.only(top: 15),
        itemCount: state.addressProvinceList.length,
        itemBuilder: (BuildContext context, int index) {
          return _getListItem(index);
        },
        physics: new BouncingScrollPhysics(),
        shrinkWrap: true,
      );
      pages.add(page);
    }
    return pages;
  }

  /**
   *创建每个界面的item显示
   */
  Widget _getListItem(int index) {

    // ProvinceInfoModel children = state.datas[state.currentTabPos][index];
    AddressItemModel children = state.addressProvinceList[index];

    var itemName = "";
    itemName = children.addressName;
    itemName = "${index}";
    if (index == 0) {

    }

    return GestureDetector(
      child: Container(
        alignment: Alignment.centerLeft,
        color: Colors.white,
        height: 50,
        padding: new EdgeInsets.only(left: 15),
        child: Text(
          itemName,
          style: TextStyle(
            fontSize: 15,
            color: state.selectDatas[state.currentTabPos] == children.addressId ? Colors.red : Colors.red,
          ),
        ),

      ),
      onTap: () {
        if (!mounted) {
          return;
        }
        // setState(() {
        //   if (state.currentTabPos > 0 && index == 0) {
        //     Navigator.pop(context);
        //     return;
        //   }
        //   // if (children.children != null && children.children.length > 0) {//这是选中的tab还有下级数据时
        //   if (children.prv_name.length > 0) {//这是选中的tab还有下级数据时
        //     // _tabs[currentTabPos] = children.name;
        //     state.tabs[state.currentTabPos] = children.prv_name;
        //
        //     state.currentTabPos++;
        //     // //加上一条【暂不选择】的空数据
        //     // if(children.children[0].id != "-1") {
        //     //   children.children.insert(0, new ProvinceInfoModel("-1", [], "暂不选择"));
        //     // }
        //     // // if(children["children"][0]["value"] != "-1") {
        //     // //   // list.add({"id": data["value"], "children": data["children"], "name": data["label"]});
        //     // //   children["children"].insert(0, {"id": "-1", "children": [], "name": "暂不选择"});
        //     // // }
        //
        //     //修改datas的数据源
        //     // datas[currentTabPos] = children.children;
        //     // selectDatas[currentTabPos - 1] = children.id;
        //     // selectNameDatas[currentTabPos - 1] = children.name;
        //     state.selectDatas[state.currentTabPos - 1] = children.prv_num_id;
        //     state.selectNameDatas[state.currentTabPos - 1] = children.prv_name;
        //
        //     state.tabs.add("请选择");
        //     state.tabController.animateTo(state.currentTabPos);
        //   } else {//这是选中的tab没有下级数据时
        //     // _tabs[currentTabPos] = children.name;
        //     // selectDatas[currentTabPos] = children.id;
        //     // selectNameDatas[currentTabPos] = children.name;
        //     state.tabs[state.currentTabPos] = children.prv_name;
        //     state.selectDatas[state.currentTabPos] = children.prv_num_id;
        //     state.selectNameDatas[state.currentTabPos] = children.prv_name;
        //
        //     Navigator.pop(context);
        //   }
        //   //将选中的区域id添加到集合，根据自己的业务去甄别
        //   List<String> areaIds = [];
        //   for(int i = 0; i < state.selectDatas.length; i++) {
        //     areaIds.add(state.selectDatas[i]);
        //   }
        //   //这个是处理选中的名称拼接，根据自己的业务去甄别
        //   String names = "";
        //   for(int i = 0; i < state.selectNameDatas.length; i++) {
        //     if (i == state.selectNameDatas.length - 1) {
        //       names += state.selectNameDatas[i];
        //     } else {
        //       names += "${state.selectNameDatas[i]}-";
        //     }
        //   }
        //
        //   //将选中的数据实时回调到需要的地方
        //   widget.eventAreaDialogCallBack(names, areaIds);
        // });
      },
    );
  }
}